//
//  LocationManager.swift
//  XUYIProject
//
//  Created by 叁拾叁 on 2020/7/16.
//  Copyright © 2020 叁拾叁. All rights reserved.
//

import UIKit
import MapKit

public class SYLocationManager: NSObject, CLLocationManagerDelegate {
    
    public let manager = CLLocationManager()
    public weak var locationProtocol: LocationProtocol?
    public static let Shared = LocationManager()
    public override init() {
        super.init()
        
        
        manager.delegate = self
        //控制定位精度,越高耗电量越
        manager.desiredAccuracy = kCLLocationAccuracyBest
        
        if #available(iOS 8.0, *) {
            manager.requestWhenInUseAuthorization()
            manager.requestAlwaysAuthorization()
        }
    }
    
    public func startLocation()  {
        
        let status  = CLLocationManager.authorizationStatus()
        
        if status == .notDetermined {
            manager.requestWhenInUseAuthorization()
            return
        }
         
        if status == .denied || status == .restricted {
            if let p = locationProtocol, let vc = p as? UIViewController {
                let alert = UIAlertController(title: "提示", message: "获取定位权限失败，请在设置中打开定位", preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
                    
                }))
                vc.vg_present(alert, animated: true, completion: nil)
            } else {
                locationProtocol?.getGPSAuthorizationFailure()
            }
             return
        }
        manager.stopUpdatingLocation()
        manager.startUpdatingLocation()
    }
    
    public func stopLocation() {
        manager.stopUpdatingLocation()
    }
    
    // CLLocationManagerDelegate
    // 每隔一段时间就会调用
    public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        for (_, loc) in locations.enumerated() {
            let l: CLLocationCoordinate2D = loc.coordinate
            let lat = l.latitude
            let lng = l.longitude
            locationProtocol?.getGPSSuccess(latitude: lat, longitude: lng)
        }
    }

    public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {

        print("无法获取位置信息 \(error.localizedDescription)")
        locationProtocol?.getGPSFailure(error: error)
    }
    
}
